package com.lcf.study.leetcode;

import com.lcf.study.Util;
import com.lcf.study.model.TreeNode;

import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by 哈兹米 on 2022-10-31.
 * 107. 二叉树的层序遍历 II
 * <p>
 * 给你二叉树的根节点 root ，返回其节点值 自底向上的层序遍历 。 （即按从叶子节点所在层到根节点所在的层，逐层从左向右遍历）
 * <p>
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 * <p>
 *      3
 *    /  \
 *   9    20
 *       /  \
 *      15   7
 * 返回其层次遍历结果：
 * <p>
 * 输入：root = [3,9,20,null,null,15,7]
 * 输出：[[15,7],[9,20],[3]]
 * 输入：root = [1]
 * 输出：[[1]]
 * <p>
 * 链接：https://leetcode.cn/problems/binary-tree-level-order-traversal-ii
 */
public class _107_levelOrderBottom {

    public static void main(String[] args) {
        _107_levelOrderBottom levelOrderBottom = new _107_levelOrderBottom();
        TreeNode treeNode = Util.generateTreeNode(new Integer[]{3, 9, 20, null, null, 15, 7});
        List<List<Integer>> result = levelOrderBottom.levelOrderBottom(treeNode);
        Util.printLists(result);
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> result = new LinkedList<>();
        if (null == root) {
            return result;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int count = queue.size();
            List<Integer> level = new LinkedList<>();
            for (int i = 0; i < count; i++) {
                TreeNode curNode = queue.poll();
                if (null == curNode) {
                    continue;
                }
                level.add(curNode.val);
                if (curNode.left != null) {
                    queue.offer(curNode.left);
                }
                if (curNode.right != null) {
                    queue.offer(curNode.right);
                }
            }
            result.add(0, level);
        }
        return result;
    }
}
